package cn.rht.study.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.web.multipart.MultipartFile;

import cn.rht.study.controller.ex.FileIsEmptyException;
import cn.rht.study.controller.ex.FileStateException;
import cn.rht.study.controller.ex.FileTypeNotSupportException;
import cn.rht.study.controller.ex.FileUploadException;
import cn.rht.study.controller.ex.FileUploadIOException;

public class UploadUtils {

	/** 头像图片类型白名单 */
	private static final List<String> TYPES = new ArrayList<String>();

	private static final long AVATAR_MAX_SIZE = 800 * 1024;
	static {
		TYPES.add("image/jpeg");
		TYPES.add("image/png");
	}
	public static String uploadImg(MultipartFile file,HttpServletRequest request)throws FileUploadException {
		//图片是否为空
		if (file.isEmpty()) {
			throw new FileIsEmptyException("上传头像失败,请上传有效头像图片");
		}

		// 如果文件大小超过限制,则抛出文件大小异常
		if (file.getSize() > AVATAR_MAX_SIZE) {
			throw new FileIsEmptyException("上传头像失败,文件大小超出" + (AVATAR_MAX_SIZE / 1024) + "Kb限制");
		}

		// 如果文件类型为不支持上传类型,则抛出文件类型不支持异常
		if (!TYPES.contains(file.getContentType())) {
			throw new FileTypeNotSupportException("上传头像失败,请上传有效图片类型(jpg或png格式图片)");
		}

		// 获取文件夹路径
//		String parentDiv = request.getServletContext().getRealPath("media/picture");
		String parentDiv = "F:/media/picture";
		// 创建文件夹文件对象
		File parent = new File(parentDiv);
		// 如果该文件夹不存在,则创建该文件夹
		if (!parent.exists()) {
			parent.mkdirs();
		}
		// 获取原始文件名
		String originalFilename = file.getOriginalFilename();
		// 获取保存的路径
		String avatar = "/media/picture" + "/" + originalFilename;
		// 设置保存文件的路径
		File dest = new File(parent, originalFilename);
		try {
			// 执行保存操作
			file.transferTo(dest);
		} catch (IllegalStateException e) {
			throw new FileStateException("上传头像失败,请上传有效");
		} catch (IOException e) {
			throw new FileUploadIOException("上传头像失败,请再次尝试");
		}
		return avatar;
	}

	public static String upload(MultipartFile file) throws IOException {
		//读取工具类的数据
		String endpoint = OssProperies.END_POINT;
		String accessKeyId = OssProperies.ACCESS_KEY_ID;
		String accessKeySecret = OssProperies.ACCESS_KEY_SECRET;
		String bucketName = OssProperies.BUCKET_NAME;
		//连接oss客户端
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		// 上传文件流
		InputStream inputStream = file.getInputStream();
		String fileName = file.getOriginalFilename();
		String fileExtension = fileName.substring(fileName.lastIndexOf("."));
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int date = c.get(Calendar.DATE);
		//自己看情况
		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);
		int second = c.get(Calendar.SECOND);
		String url = year+"/"+month+"-"+date+"/"+hour+minute+second;
		// meta设置请求头
		ObjectMetadata meta = new ObjectMetadata();
		meta.setContentType(getContentType(fileName));
		ossClient.putObject(bucketName, url+fileExtension, inputStream, meta);
		//关闭ossClient
		ossClient.shutdown();

		//返回上传之后地址，拼接地址
		String uploadUrl = "https://"+bucketName+"."+endpoint+"/"+url+fileExtension;
		return uploadUrl;
	}
	/** 
	      * 通过文件名判断并获取OSS服务文件上传时文件的contentType 
	      * @param fileName 文件名 
	      * @return 文件的contentType 
	      */
	public static String getContentType(String fileName){
		//文件的后缀名  
		String fileExtension = fileName.substring(fileName.lastIndexOf("."));
		if(".jpg".equalsIgnoreCase(fileExtension)) {
			return "image/jpg";
		}
		if(".bmp".equalsIgnoreCase(fileExtension)) {
			return "image/bmp";
		}
		if(".gif".equalsIgnoreCase(fileExtension)) {
			return "image/gif";
		}
		if(".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension) || ".png".equalsIgnoreCase(fileExtension) ) {
			return "image/jpeg";
		}
		if(".html".equalsIgnoreCase(fileExtension)) {
			return "text/html";
		}
		if(".txt".equalsIgnoreCase(fileExtension)) {
			return "text/plain";
		}
		if(".vsd".equalsIgnoreCase(fileExtension)) {
			return "application/vnd.visio";
		}
		if(".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
			return "application/vnd.ms-powerpoint";
		}
		if(".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
			return "application/msword";
		}
		if(".xml".equalsIgnoreCase(fileExtension)) {
			return "text/xml";
		}
		//默认返回类型  
		return "image/jpeg";
	}
}
